package org.xczy.core.config.interceptorConfig;

import com.alibaba.fastjson2.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.xczy.core.common.result.Result;
import org.xczy.core.utils.JWT;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Log4j2
public class JwtValidateInterceptor implements HandlerInterceptor {

  @Resource
  private JWT jwt;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    try {
      String token = request.getHeader("token");
      log.debug(request.getRequestURI() + "需要验证：" + token);
      if (token != null) {
        try {
          jwt.parseToken(token);
          log.debug(request.getRequestURI() + "验证通过");
          return true;
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
      log.debug(request.getRequestURI() + "验证失败，禁止通过");
      response.setContentType("application/json;charset=utf-8");
      Result<Object> fail = Result.fail("JWT无效，请重新登录");
      response.getWriter().write(JSON.toJSONString(fail));
      return false;   // 拦截
    }catch (Exception e){
      log.info("没有token");
      return false;
    }
  }

}
